package cn.wolfcode.p2p.util;

import cn.wolfcode.p2p.base.exception.CustomerException;
import org.springframework.util.StringUtils;

import java.util.regex.Pattern;

/**
 * 断言工具
 */
public class AssertUtil {

    /**
     * 手机号验证码规则
     */
    private static final String REGEX_MOBILE = "^((17[0-9])|(14[0-9])|(13[0-9])|(15[0-9])|(18[0,0-9]))\\d{8}$";

    private static final AssertUtil instance = new AssertUtil();

    private AssertUtil(){

    }

    public static AssertUtil instance(){
        return instance ;
    }

    /**
     * 断言字符串不为空
     */
    public AssertUtil isNotNull(String str , String errorMsg){
        if(!StringUtils.hasLength(str)){
            throw new CustomerException(errorMsg);
        }
        return this;
    }

    /**
     * 断言对象不为空
     */
    public AssertUtil isNotNull(Object obj , String errorMsg){
        if(obj == null){
            throw new CustomerException(errorMsg);
        }
        return this;
    }
    /**
     * 断言对象为空
     */
    public AssertUtil isNull(Object obj , String errorMsg){
        if(obj != null){
            throw new CustomerException(errorMsg);
        }
        return this;
    }


    /**
     * 断言字符串必须满足长度
     */
    public AssertUtil isLength(String str, int length, String errorMsg) {
        isNotNull(str,errorMsg);
        if(str.length() != length){
            throw new CustomerException(errorMsg);
        }
        return this;
    }

    /*
      断言手机号
   */
    public AssertUtil isMobile(String mobile,String errorMsg) {
        if(!Pattern.matches(REGEX_MOBILE, mobile)){
            throw new CustomerException(errorMsg);
        }
        return this;
    }

    /**
     * 断言false，如果b为true，抛出异常
     */
    public AssertUtil isFalse(boolean b, String errorMsg) {
        if(b){
            throw new CustomerException(errorMsg);
        }
        return this;
    }

    /**
     * 断言字符串范围长度
     */
    public AssertUtil isRangeLength(String str, int minLength, int maxLength, String errorMsg) {
        isNotNull(str,errorMsg);
        if(str.length() < minLength || str.length() > maxLength){
            throw new CustomerException(errorMsg);
        }
        return this;
    }

    /**
     * 断言两个字符串一致
     */
    public AssertUtil isEquals(String str1, String str2, String errorMsg) {
        isNotNull(str1,errorMsg);
        isNotNull(str2,errorMsg);
        if(!str1.equals(str2)){
            throw new CustomerException(errorMsg);
        }
        return this;
    }


}
